//
//  UCDownloadArea.m
//  SDK开发版本
//
//  Created by 北京国泰北斗科技有限公司 on 2016/12/15.
//  Copyright © 2016年 北京国泰北斗科技有限公司. All rights reserved.
//

#define degreesToRadians(x) (M_PI*(x)/180.0)

#import "UCDownloadArea.h"
#import <GoogleMaps/GoogleMaps.h>
#import "UCPath.h"

NSString * const kStartX = @"startX";
NSString * const kStartY = @"startY";
NSString * const kEndX = @"endX";
NSString * const kEndY = @"endY";

@interface UCDownloadArea()
@property(nonatomic,readwrite,strong)NSMutableArray *levelArray;
@property(nonatomic,readwrite,assign)double sumMemory;
@property(nonatomic,assign,readwrite)int64_t sumTotalBytesWritten;
@property(nonatomic,assign,readwrite)long long sumCount;
@property(nonatomic,assign,readwrite)NSInteger x;
@property(nonatomic,assign,readwrite)NSInteger y;
@property(nonatomic,assign,readwrite)NSInteger z;

@end

@implementation UCDownloadArea

- (NSMutableArray *)levelArray{
    if (!_levelArray) {
        _levelArray = [NSMutableArray array];
    }
    return _levelArray;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeInt64:self.sumCount forKey:@"sumCount"];
    [aCoder encodeDouble:self.sumMemory forKey:@"sumMemory"];
    [aCoder encodeObject:self.levelArray forKey:@"levelArray"];
    [aCoder encodeInt64:self.sumTotalBytesWritten forKey:@"sumTotalBytesWritten"];
    [aCoder encodeFloat:self.progress forKey:@"progress"];
    [aCoder encodeFloat:self.downloadCount forKey:@"downloadCount"];
    [aCoder encodeInteger:self.x forKey:@"x"];
    [aCoder encodeInteger:self.y forKey:@"y"];
    [aCoder encodeInteger:self.z forKey:@"z"];
    [aCoder encodeObject:self.mapType forKey:@"mapType"];
    [aCoder encodeObject:self.data forKey:@"data"];
    [aCoder encodeInteger:self.progressState forKey:@"progressState"];
    [aCoder encodeObject:self.cacheName forKey:@"cacheName"];
}

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    self.sumCount = [aDecoder decodeInt64ForKey:@"sumCount"];
    self.sumMemory = [aDecoder decodeDoubleForKey:@"sumMemory"];
    self.levelArray = [aDecoder decodeObjectForKey:@"levelArray"];
    self.sumTotalBytesWritten = [aDecoder decodeIntegerForKey:@"sumTotalBytesWritten"];
    self.progress = [aDecoder decodeFloatForKey:@"progress"];
    self.downloadCount = [aDecoder decodeFloatForKey:@"downloadCount"];
    self.x = [aDecoder decodeIntegerForKey:@"x"];
    self.y = [aDecoder decodeIntegerForKey:@"y"];
    self.z = [aDecoder decodeIntegerForKey:@"z"];
    self.mapType = [aDecoder decodeObjectForKey:@"mapType"];
    self.data = [aDecoder decodeObjectForKey:@"data"];
    self.progressState = [aDecoder decodeIntegerForKey:@"progressState"];
    self.cacheName = [aDecoder decodeObjectForKey:@"cacheName"];
    
    return self;
}

- (instancetype)initGetDownloadAreaWith:(UCPath *)path withLevelsSet:(NSArray *)levelsSet{
    self = [super init];
    if (self) {
        self.sumMemory = 0.0;
        self.sumCount = 0;
        self.sumTotalBytesWritten = 0;
        self.x = -1;
        self.y = -1;
        self.z = -1;
        
        self = [[UCDownloadArea alloc] init];
        
        GMSCoordinateBounds *bounds;
        for (int i = 0; i < path.count; i++) {
            CLLocationCoordinate2D southwestCoordinate = [path coordinateAtIndex:0];
            CLLocationCoordinate2D northeastCoordinate = [path coordinateAtIndex:0];
            
            CLLocationCoordinate2D position = [path coordinateAtIndex:i];
            if (southwestCoordinate.latitude > fabs(position.latitude)) southwestCoordinate.latitude = position.latitude;
            if (southwestCoordinate.longitude > fabs(position.longitude)) southwestCoordinate.longitude = position.longitude;
            if (northeastCoordinate.latitude < fabs(position.latitude)) northeastCoordinate.latitude = position.latitude;
            if (northeastCoordinate.longitude < fabs(position.longitude)) northeastCoordinate.longitude = position.longitude;
            bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:southwestCoordinate coordinate:northeastCoordinate];
        }
        //        dispatch_async(dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        for (int z = 0; z<levelsSet.count; z++) {
            @autoreleasepool {
                int startX = [[[self toTile:[levelsSet[z] intValue]
                                  longitude:bounds.southWest.longitude
                                   latitude:bounds.northEast.latitude] firstObject] intValue];
                int startY = [[[self toTile:[levelsSet[z] intValue]
                                  longitude:bounds.southWest.longitude
                                   latitude:bounds.northEast.latitude] lastObject] intValue];
                
                int endX = [[[self toTile:[levelsSet[z] intValue]
                                longitude:bounds.northEast.longitude
                                 latitude:bounds.southWest.latitude] firstObject] intValue];
                int endY = [[[self toTile:[levelsSet[z] intValue]
                                longitude:bounds.northEast.longitude
                                 latitude:bounds.southWest.latitude] lastObject] intValue];
                
                _sumCount += (endX+1 - startX) * (endY+1 - startY);
                
                NSMutableDictionary *levelDic = [NSMutableDictionary dictionary];
                NSMutableDictionary *dobulexy = [NSMutableDictionary new];
                [dobulexy setValue:[NSNumber numberWithInt:startX] forKey:kStartX];
                [dobulexy setValue:[NSNumber numberWithInt:startY] forKey:kStartY];
                [dobulexy setValue:[NSNumber numberWithInt:endX] forKey:kEndX];
                [dobulexy setValue:[NSNumber numberWithInt:endY] forKey:kEndY];
                [levelDic setValue:dobulexy forKey:[NSString stringWithFormat:@"%d",[levelsSet[z] intValue]]];
                [self.levelArray addObject:levelDic];
            }
            _sumMemory = _sumCount * 50 / 1024;
        }
    }
    return self;
}

- (NSArray *)toTile:(NSInteger)z longitude:(double)lon latitude:(double)lat{
    
    double n = pow(2, z);
    double tileX = ((lon + 180) / 360) * n;
    double tileY = (1 - (log(tan(degreesToRadians(lat)) + (1 / cos(degreesToRadians(lat)))) / M_PI)) / 2 * n;
    return [NSArray arrayWithObjects:[NSNumber numberWithDouble:tileX], [NSNumber numberWithDouble:tileY],nil];
}

- (void)getDownloadProgressWith:(int64_t)totalBytesWritten{
    
    _sumTotalBytesWritten += totalBytesWritten;
}
@end
